package com.cs.micro.mail.web;

import com.cs.base.common.support.SimpleResult;
import com.cs.base.common.support.SimpleStatusCode;
import com.cs.micro.mail.support.FtlUtils;
import com.cs.micro.mail.support.SimpleMsgPo;
import com.cs.micro.mail.support.TemplateMsgPo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;

import static com.cs.base.common.support.SimpleResult.build;
import static com.cs.base.common.support.SimpleResult.ok;

/**
 * 邮件发送
 *
 * @author wangjiahao
 * @version 1.0
 * @className MailSender
 * @since 2019-03-28 11:13
 */
@Api(tags = "邮件发送")
@RestController
@RequestMapping("/i/mail")
public class MailSendCtrl {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @PostMapping("/simple/send")
    @ApiOperation("发送普通邮件")
    public SimpleResult send(@RequestBody SimpleMsgPo po) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //邮件发送人
        simpleMailMessage.setFrom(fromEmail);
        //邮件接收人
        simpleMailMessage.setTo(po.getEmail());
        //邮件主题
        simpleMailMessage.setSubject(po.getSubject());
        //邮件内容
        simpleMailMessage.setText(po.getContent());
        try {
            javaMailSender.send(simpleMailMessage);
            return ok();
        } catch (MailException e) {
            return build(SimpleStatusCode.FAIL);
        }
    }

    @PostMapping("/template/send")
    @ApiOperation("发送freemarker模板邮件")
    public SimpleResult sendFtl(@RequestBody TemplateMsgPo po) {

        try {

            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(fromEmail);
            helper.setTo(po.getEmail());

            Map<String, Object> model = new HashMap<>();
            model.put("content", po.getContent());
            model.put("title", "标题Mail中使用了FreeMarker");
            String text = FtlUtils.render("demo.ftl", model);

            helper.setText(text, true);

            javaMailSender.send(message);
            return ok();
        } catch (Exception e) {
            return build(SimpleStatusCode.FAIL);
        }
    }

}
